package com.ironman.mes.plugin.common;

import lombok.extern.slf4j.Slf4j;
import org.noear.dami.DamiConfig;
import org.noear.dami.bus.impl.RoutingPath;
import org.noear.dami.bus.impl.TopicRouterPatterned;
import org.noear.solon.Solon;
import org.noear.solon.core.AppContext;
import org.noear.solon.core.Plugin;
import org.noear.solon.core.Props;
import org.noear.solon.core.event.EventBus;
import org.noear.solon.core.event.EventListener;

import java.util.Collections;
import java.util.List;

@Slf4j
public abstract class XPlugin implements Plugin {

    private AppContext pluginContext;

    private String pluginName;

    public abstract List<String> configYaml(String env);

    /**
     * 主包之外的包
     */
    public List<String> scanOtherPackage() {
        return Collections.singletonList("com.ironman.mes.plugin.common");
    }

    public abstract Class<?> clazz();

    public abstract void preStop(AppContext pluginContext);

    @Override
    public void start(AppContext context) throws Throwable {
        log.info("Plugin start");
        DamiConfig.configure(new TopicRouterPatterned<>(RoutingPath::new));

        this.pluginContext = context;
        Props props = this.pluginContext.cfg();

        String env = Solon.app().cfg().env();
        List<String> configYamlList = configYaml(env);
        log.info("{}", configYamlList);
        for (String configYaml : configYamlList) {
            context.cfg().loadAdd(configYaml);
        }

        List<String> basePackageList = scanOtherPackage();
        for (String basePackage : basePackageList) {
            context.beanScan(basePackage);
        }

        this.pluginContext.beanScan(clazz());
        this.pluginName = props.getProperty("plugin.name", "未知");
        log.info("【{}】插件已开启", pluginName);
    }

    @Override
    public void prestop() throws Throwable {
        log.info("Plugin preStop");
        preStop(this.pluginContext);
    }

    @Override
    public void stop() throws Throwable {
        //移除事件订阅
        this.pluginContext.beanForeach(bw -> {
            if (bw.raw() instanceof EventListener) {
                EventBus.unsubscribe(bw.raw());
            }
        });
        log.info("【{}】插件关闭", pluginName);
    }
}
